<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\model\OrderTemporary;
use app\common\tool\Result;
use think\facade\View;
use think\Response;

class Order extends Base
{
    public function index(): string|Response
    {
        $temporary = OrderTemporary::getTemporary($this->user->id);
        if ($temporary['code'] != 1) return redirect('/');
        View::assign('temporary', $temporary['data']);

        return View::fetch();
    }

    public function submit(): Response
    {
        $param = $this->request->post();
        $result = OrderTemporary::submit($param, $this->user);
        if ($result['code'] != 1) {
            return Result::fail($result['msg']);
        }

        return Result::fastReturn([
            'code' => 1,
            'msg' => '订单已生成',
            'url' => url('order/payment')->build() . '?id=' . $result['data']
        ]);
    }

    public function payment($id): string|Response
    {
        $info = OrderTemporary::getPayment($id, $this->user);
        if (empty($info['data'])) return redirect(url('user/index')->build());
        View::assign([
            'info' => $info['data']['order'],
            'method' => $info['data']['method']
        ]);

        return View::fetch();
    }

    public function confirmPayment(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(OrderTemporary::payment($param, $this->user));
    }

    public function success(): string
    {
        return View::fetch();
    }

    public function myOrder(): string
    {
        return View::fetch();
    }

    public function getList(): Response
    {
        $param = $this->request->get();
        $map['uid'] = $this->user->id;
        if (!empty($param['type'])) {
            $map['status'] = $param['type'];
        }

        return Result::fastReturn(OrderTemporary::getPageList($map, 'id,sn,total_amount,real_amount,status,create_time',
            $this->getPage(), $this->getLimit(), false, ['productsField'], [], [], [], [], '', ['status_name']));
    }

    public function details($id): string|Response
    {
        $info = OrderTemporary::with(['productsField', 'p', 'c', 'd', 'express'])
            ->where(['id' => $id, 'uid' => $this->user->id])->find();
        if (empty($info)) return redirect('/');
        $info->friendlyText = getProductOrderFriendly($info->status);
        View::assign('info', $info);

        return View::fetch();
    }

    public function edit(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(OrderTemporary::edit($param, $this->user));
    }
}